package data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.UserModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class UserData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "";
	
	private int limit = 20;
	
	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public UserData() {
		try {
			ObjectifyService.register(UserModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<UserModel> list() {
		ArrayList<UserModel> users = new ArrayList<UserModel>();
		
		int start = (page - 1) * limit;
		Query<UserModel> q = ofy.query(UserModel.class).limit(limit).offset(start);
		for (UserModel user: q) {
			users.add(user);
		}
		
		return users;
	}
	
	public void insert(UserModel user) {
		if (cache != null) {
			cache.put(prefix + user.getUsername(), user);
		}
		ofy.put(user);
	}
	
	public void delete(UserModel user) {
		if (cache != null && cache.containsKey(prefix + user.getUsername())) {
			cache.remove(prefix + user.getUsername());
		}
		
		ofy.delete(user);
	}
	
	public UserModel getUser(String username) {
		UserModel user = new UserModel();
		if (cache != null && cache.containsKey(prefix + username)) {
			user = (UserModel) cache.get(prefix + username);
		} else {
			try {
				user = ofy.get(new Key<UserModel>(UserModel.class, username));
				cache.put(prefix + username, user);
			} catch (Exception e) {
				user = null;
			}
		}
		return user;
	}
	
	public boolean checkUserExists(String username) {
		boolean exists = false;
		UserModel user = getUser(username);
		if (user != null) {
			exists = true;
		}
		return exists;
	}
}
